package com.powernode.controller;

import com.github.pagehelper.PageInfo;
import com.powernode.common.Constants;
import com.powernode.common.Result;
import com.powernode.domain.Customer;
import com.powernode.domain.User;
import com.powernode.dto.CustomerDto;
import com.powernode.service.CustomerService;
import com.powernode.utils.WebMvcUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 内容:
 * 作者:
 */
@RestController
@RequestMapping("customer")
public class CustomerController {

    @Resource
    private CustomerService customerService;


    /**
     *分页查询
     */
    @GetMapping("list.do")
    public Result list(CustomerDto customerDto){
        //判断当前登陆的是否是管理员
        User currentUser = WebMvcUtils.getCurrentUser();
        //如果是业务员，那么我们只能查询当前业务员的客户
        if(currentUser.getRole().equals(Constants.ROLE_2)){
            customerDto.setUserId(currentUser.getId());
        }
        //查询数据
        PageInfo<Customer> pageInfo=this.customerService.queryCustomerForPage(customerDto);
        return new Result(0,"查询成功",pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 添加
     */
    @PostMapping("addCustomer.do")
    public Result addCustomer(Customer customer){
        try {
            //补充数据
            customer.setDeleted(Constants.DELETED_1);
            customer.setCreateTime(new Date());
            customer.setUserId(WebMvcUtils.getCurrentUser().getId());
            //保存
            this.customerService.insertSelective(customer);
            return Result.ADD_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return Result.ADD_ERROR;
        }
    }
    /**
     * 修改
     */
    @PostMapping("updateCustomer.do")
    public Result updateCustomer(Customer customer){
        try {
            //保存
            this.customerService.updateByPrimaryKeySelective(customer);
            return Result.UPDATE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return Result.UPDATE_ERROR;
        }
    }


    /**
     * 删除
     */
    @PostMapping("del.do")
    public Result delete(Integer id){
        try {
            Customer customer=new Customer();
            customer.setId(id);
            customer.setDeleted(Constants.DELETED_2);
            //保存
            this.customerService.updateByPrimaryKeySelective(customer);
            return Result.DEL_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return Result.DEL_ERROR;
        }
    }
    /**
     * 转移客户
     */
    @PostMapping("changeCustomerUser.do")
    public Result changeCustomerUser(Integer userId, Integer[] customerIds){
        try {
            this.customerService.changeCustomerUser(userId,customerIds);
            return Result.OPT_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return Result.OPT_ERROR;
        }
    }
}
